import axios from 'axios'
import { useRouter } from "vue-router"
import { ElMessage } from "element-plus";
import { rewritePath } from "@/config/index.js"



const service = axios.create({
    baseURL: rewritePath,
    timeout: 30000, // 请求超时时间，设置30秒。有些接口事务多能会长
})

// 请求发起拦截
service.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('tokenSeller')
        if (token) config.headers.authorization = `Bearer ${token}`
        return config
    },
    (error) => {
        // do something with request error
        return Promise.reject(error)
    },
)

// 请求响应拦截
service.interceptors.response.use(
    (response) => {
        const res = response.data
        console.log(res.code)
        if (res.code === 401) {
            const router = useRouter()
            router.push('/login')
        }
        if (res.code === 500) {
            ElMessage.error(res.msg)
            return Promise.reject(res)
        }
        if (response.error) {
            throw new Error(response.error.message || '响应错误');
        }
        if (response.status !== 200) {
            ElMessage.error(response.msg);
            throw new Error(response);
        }
        return res
    },
    (error) => {
        let { message } = error
        if (message === 'Network Error') {
            message = 'ERROR:网络连接异常'
        } else if (message.includes('timeout')) {
            message = 'ERROR:系统接口请求超时'
        } else if (message.includes('Request failed with status code')) {
            message = 'ERROR:接口返回状态' + message.substr(message.length - 3) + '异常'
        }
        ElMessage.error(message)
        return Promise.reject(error)
    },
)

export default service
